import { defineStore } from 'pinia';
import * as Cesium from 'cesium';

export const useFengmianStore = defineStore('fengmianCenter', {
  state: () => ({
    viewer: null, // Cesium Viewer 实例
    fengmianCenterData: [], // 锋面中心数据
    linePrimitive: null, // 存储 PrimitiveCollection 实例
    isVisible: false, // 显隐状态
  }),
  actions: {
    // 设置 Viewer
    setViewer(viewer) {
      this.viewer = viewer;
    },
    setIsVisible(isVisible) {
      this.isVisible = isVisible; 
    },
    // 设置锋面中心数据
    setFengmianCenterData(data) {
      this.fengmianCenterData = data;
    },

    // 创建所有线段
    createLineSegments() {
      // 清理旧数据
      if (this.linePrimitive) {
        this.viewer.scene.primitives.remove(this.linePrimitive);
      }

      // 使用 PrimitiveCollection 替代 PolylineCollection
      this.linePrimitive = this.viewer.scene.primitives.add(
        new Cesium.PrimitiveCollection()
      );

      // 遍历每个起点-终点对
      for (let i = 0; i < this.fengmianCenterData.variables.line_point_coordinates.data[0].length; i++) {
        const [startLon, startLat, endLon, endLat] = [
          this.fengmianCenterData.variables.line_point_coordinates.data[0][i],
          this.fengmianCenterData.variables.line_point_coordinates.data[1][i],
          this.fengmianCenterData.variables.line_point_coordinates.data[2][i],
          this.fengmianCenterData.variables.line_point_coordinates.data[3][i],
        ];

        if (this.isValidCoordinate(startLon, startLat) && this.isValidCoordinate(endLon, endLat)) {
          // 创建几何实例
          const geometryInstance = new Cesium.GeometryInstance({
            geometry: new Cesium.PolylineGeometry({
              positions: [
                Cesium.Cartesian3.fromDegrees(startLon, startLat, 100),
                Cesium.Cartesian3.fromDegrees(endLon, endLat, 100),
              ],
              width: 3,
              vertexFormat: Cesium.PolylineMaterialAppearance.VERTEX_FORMAT,
            }),
          });

          // 使用基本颜色材质
          const appearance = new Cesium.PolylineMaterialAppearance({
            material: Cesium.Material.fromType("Color", {
              color: Cesium.Color.BLUE, // 更改颜色以区分
            }),
          });

          // 添加 Primitive
          this.linePrimitive.add(
            new Cesium.Primitive({
              geometryInstances: geometryInstance,
              appearance: appearance,
              asynchronous: false,
            })
          );
        }
      }

      // 强制重绘
      this.viewer.scene.requestRender();
    },

    // 坐标验证函数
    isValidCoordinate(lon, lat) {
      const valid = !isNaN(lon) && !isNaN(lat) && lon >= -180 && lon <= 180 && lat >= -90 && lat <= 90;
      if (!valid) console.warn(`Invalid coordinate: ${lon}, ${lat}`);
      return valid;
    },

    // 初始化 Viewer 配置
    configureViewer() {
      this.viewer.scene.globe.depthTestAgainstTerrain = false;
      this.viewer.scene.globe.terrainExaggeration = 1.0;
      this.viewer.scene.highDynamicRange = false;
    },

    // 执行初始化
    initialize() {
      this.configureViewer();
      this.createLineSegments();
    },

    toggleFengmianVisibility() {
      this.isVisible = !this.isVisible;
      if (this.isVisible) {
        this.initialize();
      } else {
        if (this.linePrimitive) {
          this.viewer.scene.primitives.remove(this.linePrimitive);
          this.linePrimitive = null;
        }
      }
    },
  },
});